package com.central.apps.handler.MaterialInventory;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.common.util.BLuntil;
import com.central.app.service.HandlerService;
import com.central.apps.dao.MaterialInventory.goWarehouseDao;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.apps.service.IInventoryService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.web.PageResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
//出库管理
public class GoWarehouseHandler extends LvBaseHandler {
    @Autowired
    private goWarehouseDao goWarehouseDao;
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private IInventoryService calInvQuantity;
//    @Override
//    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
////        if ("invuseApp".equals(app)){
////            if ("gq_invuse".equals(objName)) {
////                String invusenum = MapUtils.getString(data, "invusenum");
////                String lldnum = MapUtils.getString(data, "lldnum");
////                String id = MapUtils.getString(data, "id");
////                String bylldnum = goWarehouseDao.getlldnumById(id);
////                if (!lldnum.equals(bylldnum)) {
////                    goWarehouseDao.delinvuseline(invusenum);
////                    List<Map<String, Object>> pickingHandler = goWarehouseDao.getPickingHandler(lldnum);
////                    if (CollectionUtils.isNotEmpty(pickingHandler)) {
////                        for (int i = 0; i <pickingHandler.size(); i++) {
////                            Map<String, Object> map = pickingHandler.get(i);
////                            String itemnum = MapUtils.getString(map, "itemnum");
////                            String itemdesc = MapUtils.getString(map, "itemdesc");
////                            String specmodel = MapUtils.getString(map, "specmodel");
////                            String unit = MapUtils.getString(map, "unit");
////                            Integer quantity = MapUtils.getInteger(map, "quantity");
////                            String wonum = MapUtils.getString(map, "wonum");
////                            String binnum = MapUtils.getString(map, "binnum");
////                            String lotnum = MapUtils.getString(map, "lotnum");
////                            String locations = MapUtils.getString(map, "locations");
////                            HashMap<String, Object> hashMap = new HashMap<>();
////                            hashMap.put("invusenum", invusenum);
////                            hashMap.put("itemnum", itemnum);
////                            hashMap.put("itemdesc", itemdesc);
////                            hashMap.put("specmodel", specmodel);
////                            hashMap.put("unit", unit);
////                            hashMap.put("quantity", quantity);
////                            hashMap.put("wonum", wonum);
////                            hashMap.put("binnum",binnum);
////                            hashMap.put("lotnum",lotnum);
////                            hashMap.put("locations",locations);
////                            goWarehouseDao.insert(hashMap);
////                        }
////                    }
////
////                }
////                }
////            }
//
//            }


    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("invuseApp".equals(app)) {
            if ("getInvusenum".equals(type)) {
                String invusenum = MapUtils.getString(params, "invusenum");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT lldnum FROM gq_invuse WHERE invusenum = '" + invusenum + "'");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    Map<String, Object> map = bySql1.get(0);
                    String lldnum = MapUtils.getString(map, "lldnum");
                    List<Map<String, Object>> bySql = handlerService.findBySql("SELECT\n" +
                            "\ta.itemnum,\n" +
                            "\ta.quantity,\n" +
                            "\ta.wonum,\n" +
                            "\ta.binnum,\n" +
                            "\ta.lotnum,\n" +
                            "\ta.locations, \n" +
                            "\ta.unitcost, \n" +
                            "\ta.linecost \n" +
                            "FROM\n" +
                            "\tgq_itemapplyline a \n" +
                            "WHERE\n" +
                            "\tglnum = '"+lldnum+"' \n" +
                            "\tAND ( a.itemnum, a.binnum, a.lotnum, a.locations ) NOT IN (\n" +
                            "\tSELECT\n" +
                            "\t\tb.itemnum,\n" +
                            "\t\tb.binnum,\n" +
                            "\t\tb.lotnum,\n" +
                            "\t\tb.locations \n" +
                            "\tFROM\n" +
                            "\t\tgq_invuseline b \n" +
                            "WHERE\n" +
                            "\tinvusenum = '"+invusenum+"')");
                    if (CollectionUtils.isNotEmpty(bySql)) {
                        int page = 1;
                        int limit = 10;
                        if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                            page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                            limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                        }

                        List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                        return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
                    }
                }
            }
        }
        return super.operate(app, type, params);
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("invuseApp".equals(app)){
            if ("gq_invuseline".equals(objName)){
                //true为修改保存；false为新增保存
             //   String invusenum = MapUtils.getString(data, "invusenum");
                if (isUpdate==false){ Integer quantity1 = MapUtils.getInteger(data, "quantity");

                    //  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

                    data.put("grantqty",quantity1);
                    data.put("actualdate",new Date());
                }

              // handlerService.insert("gq_invuseline", data);
//                List<Map<String, Object>> bySql = handlerService.findBySql("\tSELECT lldnum FROM gq_invuse where invusenum='" + invusenum + "'");
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        String lldnum = MapUtils.getString(map, "lldnum");
//                        List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT quantity,itemnum,binnum,lotnum,locations from gq_itemapplyline where glnum ='"+lldnum+"'");
//                        if (CollectionUtils.isNotEmpty(bySql1)){
//                            for (int j=0;j<bySql1.size();j++){
//                                Map<String, Object> map1 = bySql1.get(j);
//                                Integer quantity = MapUtils.getInteger(map1, "quantity");
//                                String itemnum = MapUtils.getString(map1, "itemnum");
//                                String binnum = MapUtils.getString(map1, "binnum");
//                                String lotnum = MapUtils.getString(map1, "lotnum");
//                                String locations = MapUtils.getString(map1, "locations");
//                                handlerService.updateBySql("\tUPDATE gq_invuseline set grantqty= "+quantity+" where invusenum = '"+invusenum+"'and itemnum='"+itemnum+"'and binnum='"+binnum+"' and lotnum='"+lotnum+"' and locations='"+locations+"'");
//                                handlerService.updateBySql("\tUPDATE gq_invuseline set actualdate = createtime where invusenum = '"+invusenum+"'and itemnum='"+itemnum+"'and binnum='"+binnum+"' and lotnum='"+lotnum+"' and locations='"+locations+"'");
//                            }
//                        }
//                    }
//                }
            }
        }
        super.beforSave(app, objName, data, isUpdate);
    }
    //    @Override
//    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("invuseApp".equals(app)){
//            if ("gq_invuse".equals(objName)){
//                HashMap<String, Object> hashMap = new HashMap<>();
//                String invusenum = MapUtils.getString(data,"invusenum");
//                String lldnum = MapUtils.getString(data,"lldnum");
//                List<Map<String, Object>> pickingHandler = goWarehouseDao.getPickingHandler(lldnum);
//                if (CollectionUtils.isNotEmpty(pickingHandler)){
//                   for (int i = 0; i<pickingHandler.size();i++) {
//                       Map<String, Object> map = pickingHandler.get(i);
//                       String itemnum = MapUtils.getString(map, "itemnum");
//                       String itemdesc = MapUtils.getString(map, "itemdesc");
//                       String specmodel = MapUtils.getString(map, "specmodel");
//                       String unit = MapUtils.getString(map, "unit");
//                       String quantity = MapUtils.getString(map, "quantity");
//                       String wonum = MapUtils.getString(map, "wonum");


//    @Override
//    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("invuseApp".equals(app)){
//            if ("gq_invuseline".equals(objName)){
//                String invusenum = MapUtils.getString(data, "invusenum");
//                String lldnum = MapUtils.getString(data, "lldnum");
//                List<Map<String, Object>> bySql = handlerService.findBySql("SELECT grantqty,unitcost,linecost from gq_invuseline where invusenum = '" + invusenum + "'");
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        Integer grantqty = MapUtils.getInteger(map, "grantqty");//数量
//                        Float unitcost = MapUtils.getFloat(map, "unitcost");//单价
//                        Float linecost = MapUtils.getFloat(map, "linecost");//合计
//                        if (isUpdate==true){
//                            handlerService.updateBySql("\tUPDATE gq_invuseline set linecost=unitcost*grantqty where invusenum = '"+invusenum+"'\n");
//                        }else {
//                            handlerService.updateBySql("\tUPDATE gq_invuseline set linecost=unitcost*1 where invusenum = '"+invusenum+"'\n");
//                        }
//                    }
//                }
//            }
//        }
//        super.afterSave(app, objName, data, isUpdate);
//    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("approval")) {
            //  //审核通过后出库库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                //查询出库主表
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_invuse where id = " + id);
                String invusenum = BLuntil.getParameter(bySql.get(0), "invusenum");
                //查询出库清单
                //grantqty:出库数量 itemnum:物料编码  仓库编码：locations 批次编号 ：lotnum 库位编号：binnum
                List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT b.locations as locations,b.grantqty AS grantqty,b.itemnum AS itemnum,b.binnum as binnum,b.lotnum as lotnum FROM gq_invuse a LEFT JOIN gq_invuseline b ON a.invusenum = b.invusenum WHERE a.invusenum = '" + invusenum + "'");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    for (int i = 0; i < bySql1.size(); i++) {
                        Map<String, Object> map = bySql1.get(i);
                        String invusenum1 = MapUtils.getString(map, "invusenum");
                        Integer grantqty = MapUtils.getInteger(map, "grantqty");
                        String locations = MapUtils.getString(map, "locations");
                        String binnum = MapUtils.getString(map, "binnum");
                        String itemnum = MapUtils.getString(map, "itemnum");
                        String lotnum = MapUtils.getString(map, "lotnum");
                        // 库存余量表：  itemnum,storenum:库房，binnum：库位，batchnum：批次
                        handlerService.updateBySql("UPDATE gq_invbalances SET curbal =curbal-" + grantqty + " WHERE storenum = '" + locations + "' AND binnum = '" + binnum + "' AND itemnum ='" + itemnum + "' AND batchnum ='" + lotnum + "'");
                        handlerService.updateBySql("UPDATE gq_invbalances SET reservedqty =reservedqty-" + grantqty + " WHERE storenum = '" + locations + "' AND binnum = '" + binnum + "' AND itemnum ='" + itemnum + "' AND batchnum ='" + lotnum + "'");
                        handlerService.updateBySql("UPDATE gq_invbalances SET avblbalance =curbal - reservedqty WHERE storenum = '" + locations + "' AND binnum = '" + binnum + "' AND itemnum ='" + itemnum + "' AND batchnum ='" + lotnum + "'");
                        int grantqtyInt = grantqty.intValue();
                        calInvQuantity.updateInvQty(locations, itemnum, grantqtyInt, true);
                    }
                }
                List<Map<String, Object>> bySql2 = handlerService.findBySql("SELECT a.receiveuser as receiveuser,a.locations AS locations,a.locationsdesc AS locationsdesc,a.lldnum AS lldnum,b.itemnum AS itemnum,b.itemdesc AS itemdesc,b.specmodel AS specmodel,b.quantity AS quantity,b.unit AS unit,b.actualdate AS actualdate,b.grantqty AS grantqty\n" +
                        "FROM gq_invuse a \n" +
                        "LEFT JOIN gq_invuseline b \n" +
                        "ON a.invusenum = b.invusenum \n" +
                        "WHERE a.invusenum = '" + invusenum + "'");
                if (CollectionUtils.isNotEmpty(bySql2)) {
                    for (int j = 0; j < bySql2.size(); j++) {
                        Map<String, Object> map = bySql2.get(j);
                        String itemnum = MapUtils.getString(map, "itemnum");//物料编号
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("SELECT  description FROM gq_item WHERE itemnum ='" + itemnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql3)) {
                            for (int i = 0; i < bySql3.size(); i++) {
                                Map<String, Object> map1 = bySql3.get(i);
                                String description = MapUtils.getString(map1, "description");
                                Integer grantqty = MapUtils.getInteger(map,"grantqty");
                                //String itemdesc = MapUtils.getString(map, "itemdesc");//物料名称
                                String specmodel = MapUtils.getString(map, "specmodel");//型号
                                Integer quantity = MapUtils.getInteger(map, "quantity");//领料数量
                                String unit = MapUtils.getString(map, "unit");//单位
                                String actualdate = MapUtils.getString(map, "actualdate");//发放时间
                                String receiveuser = MapUtils.getString(map, "receiveuser");//创建人
                                String locations = MapUtils.getString(map, "locations");//库房编号
                                String locationsdesc = MapUtils.getString(map, "locationsdesc");//库房名称
                                String lldnum = MapUtils.getString(map, "lldnum");//单号
                                //组织库存交易表信息
                                HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("itemnum", itemnum);
                                hashMap.put("itemdesc", description);
                                hashMap.put("storenum", locations);
                                hashMap.put("storedesc", locationsdesc);
                                hashMap.put("quantity", grantqty);
                                hashMap.put("transdate", actualdate);
                                // handlerService.findBySql("select receiveuser from ")
                                hashMap.put("issueto", receiveuser);
                                hashMap.put("itemapplynum", lldnum);
                                //库存转移单号
                                hashMap.put("type", "出库");

                                //插入出库信息
                                handlerService.insert("gq_matusetrans", hashMap);
                            }
                        }
                    }
                }
                List<Map<String, Object>> bySql3 = handlerService.findBySql(" select lldnum from gq_invuse where invusenum ='" + invusenum + "'");//查询物料编号
                if (CollectionUtils.isNotEmpty(bySql3)){
                    for (int z=0;z<bySql3.size();z++){
                        Map<String, Object> map1 = bySql3.get(z);
                        String lldnum = MapUtils.getString(map1, "lldnum");//主表物料编号
                        List<Map<String, Object>> bySql4 = handlerService.findBySql(" select quantity,amounttoreceive,receivedlinecost,receivedqty from gq_itemapplyline where glnum ='" + lldnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql4)){
                            for (int x=0;x<bySql4.size();x++){
                                Map<String, Object> map2 = bySql4.get(x);
                                Integer quantity = MapUtils.getInteger(map2, "quantity");//领用数量
                                Integer amounttoreceive = MapUtils.getInteger(map2, "amounttoreceive");//要接收的数量
                                Float receivedlinecost = MapUtils.getFloat(map2, "receivedlinecost");//已接收行成本（不含税）
                                Float receivedqty = MapUtils.getFloat(map2, "receivedqty");//已接收数量
                                List<Map<String, Object>> bySql5 = handlerService.findBySql(" SELECT grantqty,unitcost from gq_invuseline where invusenum = '" + invusenum + "'");
                                if (CollectionUtils.isNotEmpty(bySql5)){
                                    for (int c=0;c<bySql5.size();c++){
                                        Map<String, Object> map = bySql5.get(c);
                                        Integer grantqty = MapUtils.getInteger(map, "grantqty");//出库数量
                                        Float unitcost = MapUtils.getFloat(map, "unitcost");//出库单价
                                        handlerService.updateBySql("UPDATE gq_itemapplyline set amounttoreceive = amounttoreceive -"+grantqty+" where glnum ='"+lldnum+"'");
                                        handlerService.updateBySql("UPDATE gq_itemapplyline set receivedlinecost = ("+grantqty+"*"+unitcost+") where glnum ='"+lldnum+"'");
                                        handlerService.updateBySql(" UPDATE  gq_itemapplyline set receivedqty =receivedqty+"+grantqty+" where glnum ='"+lldnum+"'");
                                    }

                                }
                            }
                        }
                    }
                }

            }
        }
    }
}

//    @Override
//    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("invuseApp".equals(app)){
//            if ("gq_invuse".equals(objName)){
//                HashMap<String, Object> hashMap = new HashMap<>();
//                String invusenum = MapUtils.getString(data,"invusenum");
//                String lldnum = MapUtils.getString(data,"lldnum");
//                List<Map<String, Object>> pickingHandler = goWarehouseDao.getPickingHandler(lldnum);
//                if (CollectionUtils.isNotEmpty(pickingHandler)){
//                   for (int i = 0; i<pickingHandler.size();i++) {
//                       Map<String, Object> map = pickingHandler.get(i);
//                       String itemnum = MapUtils.getString(map, "itemnum");
//                       String itemdesc = MapUtils.getString(map, "itemdesc");
//                       String specmodel = MapUtils.getString(map, "specmodel");
//                       String unit = MapUtils.getString(map, "unit");
//                       String quantity = MapUtils.getString(map, "quantity");
//                       String wonum = MapUtils.getString(map, "wonum");
//                       List<Map<String, Object>> bySql = handlerService.findBySql("SELECT itemnum FROM gq_invuseline where invusenum ='" + invusenum + "'");
//                       if (bySql.size() != 0) {
//                           for (int j = 0; j < bySql.size(); j++) {
//                               Map<String, Object> map1 = bySql.get(i);
//                               String itemnum1 = MapUtils.getString(map1, "itemnum");
//                               if (itemnum.equals(itemnum1)) {
//                                    break;
//                               } else if(j==bySql.size()-1){
//                                   hashMap.put("invusenum", invusenum);
//                                   hashMap.put("itemnum", itemnum);
//                                   hashMap.put("itemdesc", itemdesc);
//                                   hashMap.put("specmodel", specmodel);
//                                   hashMap.put("unit", unit);
//                                   hashMap.put("quantity", quantity);
//                                   hashMap.put("wonum", wonum);
//                                   goWarehouseDao.insert(hashMap);
//                               }
//
//                           }
//                       }else {
//                           hashMap.put("invusenum", invusenum);
//                           hashMap.put("itemnum", itemnum);
//                           hashMap.put("itemdesc", itemdesc);
//                           hashMap.put("specmodel", specmodel);
//                           hashMap.put("unit", unit);
//                           hashMap.put("quantity", quantity);
//                           hashMap.put("wonum", wonum);
//                           goWarehouseDao.insert(hashMap);
//                       }
//                   }
//                }
//            }
//        }
//    }
//}
